package ru.osu.acm.system;

import ru.osu.acm.common.config.Config;
import ru.osu.acm.common.entities.Submission;
import ru.osu.acm.common.industrial.SubmissionFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * User: Aleksey
 * Date: 17.02.2009
 * Time: 19:24:30
 */
public class SubmissionMonitor extends Thread {
    private boolean running = true;
    private boolean waiting = true;

    private Connection con;

    private void connectToDatabase() {
        String database = Config.database;
        String username = Config.username;
        String password = Config.password;

        try {
            Class.forName(Config.driver);
        }
        catch (ClassNotFoundException e) {
            Logger.logError(e);
        }
        try {
            con = DriverManager.getConnection(Config.uri + database, username, password);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void disconnectFromDatabase() {
        try {
            con.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();

        Logger.log("Submission monitor started");

        connectToDatabase();
        while (running) {
            while (waiting) {
                try {
                    sleep(5000);
                }
                catch (InterruptedException e) {
                    Logger.logError(e);
                }
            }

            ArrayList<Submission> submissions = SubmissionFactory.getSubmissionsByStatus(Tester.STATUS_RECEIVED, con, false);
            if (submissions.size() != 0) {
                Logger.log("There are new submissions [" + submissions.size() + "]");
                new Tester().test(submissions);
            }
            else {
                ArrayList<Submission> plagSubmissions = SubmissionFactory.getSubmissionsForPlagTesting(PlagTester.PLAGSTATUS_QUEUED, Tester.STATUS_ACCEPTED, con, false);
                if (plagSubmissions.size() != 0) {
                    Logger.log("There are new plagSubmissions [" + plagSubmissions.size() + "]");
                    new PlagTester().testPlag(plagSubmissions);
                }
            }

            try {
                sleep(5000);
            }
            catch (InterruptedException e) {
                Logger.logError(e);
            }
        }
        disconnectFromDatabase();
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    public boolean isWaiting() {
        return waiting;
    }

    public void setWaiting(boolean waiting) {
        this.waiting = waiting;
    }
}
